<?php

class MySQLConnect
{
	
	private $mysqli;

	public function __construct( $host, $username, $password )
	{
		
		$this->mysqli = new mysqli ( $host, $username, $password );
		
		/* check connection */
		if ( mysqli_connect_errno () )
		{
			trigger_error ( 'Database connection failure: Username/Password was incorrect.', E_USER_ERROR );
			exit ();
		} else
		{
			return $this->mysqli;
		}
	}
	/**
	 * Executes a query, and returns a array of results
	 *
	 * @param [string] $sql a query string
	 * @return [array]
	 */
	public function execute( $sql )
	{
		$result = $this->mysqli->query ( $sql );
		
			/* fetch associative array */
			while ( $row = $result->fetch_assoc () )
			{
				$array[] = $row;
			}
			
			/* free result set */
			$result->close ();
	
		/* close connection */
		$this->mysqli->close ();
		
		return $array;
	}
	
	public function analyzeQuery( $sql )
	{
		$setProfileSQL = $this->mysqli->query( 'SET profiling = 1' );
		$analyzeSQL = $this->mysqli->query( $sql );
		$showProfileSQL = $this->mysqli->query( 'SHOW PROFILE' );
		$showProfilesSQL = $this->mysqli->query( 'SHOW PROFILES' );
		
		$resultArray = array();
		$profileArray = array();
		$profilesArray = array();
		
		/* fetch associative array */
		while ( $row1 = $analyzeSQL->fetch_assoc () )
		{
			$resultArray[] = $row1;
		}
		
		/* fetch associative array */
		while ( $row2 = $showProfileSQL->fetch_assoc () )
		{
			$profileArray[] = $row2;
		}
		
		/* fetch associative array */
		while ( $row3 = $showProfilesSQL->fetch_assoc () )
		{
			$profilesArray[] = $row3;
		}
		
		$analyzedQuery[] = array( 'aProfile' => $profileArray, 'aProfiles' => $profilesArray, 'aResults' => $resultArray );
		
		/* Free all of the results */
		$analyzeSQL->close();
		$showProfileSQL->close();
		$showProfilesSQL->close();
		
		/* close connection */
		$this->mysqli->close ();
		
		
		return json_encode( $analyzedQuery );
	}
	
	
	
	
	
	

	public function doquery( $query )
	{
		return $this->mysqli->query ( $query );
	}

	public function dump( $var, $title )
	{
		print "<h4>$title</h4>";
		print "<pre>";
		print_r ( $var );
		print "</pre>";
	}

	/**
	 * @return unknown
	 */
	public function getMysqli()
	{
		return $this->mysqli;
	}

	/**
	 * @param unknown_type $mysqli
	 */
	public function setMysqli( $mysqli )
	{
		$this->mysqli = $mysqli;
	}

}
?>